package bhwz.seac3.ui.user;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.BoxLayout;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;

import bhwz.seac3.LocalBLServiceManager;
import bhwz.seac3.RMIClientBLServiceManager;
import bhwz.seac3.blservice.AutoRedisplay;
import bhwz.seac3.blservice.query.MatchQueryBLService;
import bhwz.seac3.blservice.query.PlayerQueryBLService;
import bhwz.seac3.ui.user.graphics.Graphics;
import bhwz.seac3.util.PictureManager;
import bhwz.seac3.util.SortableTable;
import bhwz.seac3.util.SortableTableModel;
import bhwz.seac3.vo.MatchVo;
import bhwz.seac3.vo.PlayerScoreTableVo;
import bhwz.seac3.vo.PlayerVo;

import javax.swing.JScrollPane;
import javax.swing.table.TableModel;

import java.awt.BorderLayout;
import java.awt.Insets;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Set;

public class PlayerDetailDialog extends JDialog implements AutoRedisplay {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	String season;
	private JPanel contentPane0;
	private JPanel contentPane;
	private SortableTable table;
	private Object[][] info;
	private final Object[] columns = { "比赛时间", "比赛队伍", "比分", "球员得分" };
	private final int width = 1400, height = 700;
	private JScrollPane scrollPaneCenter;
	private JScrollPane scrollPaneSouth;
	private PlayerVo vo;

	public PlayerDetailDialog(Frame owner, PlayerVo vo,String season) {
		super(owner);
		this.season=season;
		this.vo = vo;
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

		setVisible(true);
		setBounds(100, 0, width, height);
		this.setResizable(false);
		contentPane = new JPanel();
		setContentPane(contentPane);
		contentPane.setLayout(new BorderLayout(0, 0));
		contentPane.setBackground(Color.white);

		JPanel panelWest = new JPanel();
		panelWest.setSize(300, 500);
		panelWest.setBackground(Color.white);
		GridBagLayout gbl_panelWest = new GridBagLayout();
		gbl_panelWest.columnWidths = new int[] { 57, 184, 1, 0 };
		gbl_panelWest.rowHeights = new int[] { 214, 0, 0 };
		gbl_panelWest.columnWeights = new double[] { 1.0, 0.0, 0.0,
				Double.MIN_VALUE };
		gbl_panelWest.rowWeights = new double[] { 0.0, 1.0, Double.MIN_VALUE };
		panelWest.setLayout(gbl_panelWest);

		ImagePanel p = null;
		try {
			p = new ImagePanel(new PictureManager("png").decodeImage(vo
					.getPortraitPicture()));
		} catch (ClassNotFoundException | IOException e) {
			e.printStackTrace();
		}
		GridBagConstraints gbc_p = new GridBagConstraints();
		gbc_p.gridwidth = 2;
		gbc_p.insets = new Insets(5, 5, 5, 5);
		gbc_p.gridx = 0;
		gbc_p.gridy = 0;
		panelWest.add(p, gbc_p);

		contentPane.add(panelWest, BorderLayout.WEST);

		JPanel panelWestSouth = new JPanel();
		panelWestSouth.setBackground(Color.white);
		panelWestSouth.setLayout(null);
		GridBagConstraints gbc_panelWestSouth = new GridBagConstraints();
		gbc_panelWestSouth.gridwidth = 2;
		gbc_panelWestSouth.insets = new Insets(0, 0, 0, 5);
		gbc_panelWestSouth.fill = GridBagConstraints.BOTH;
		gbc_panelWestSouth.gridx = 0;
		gbc_panelWestSouth.gridy = 1;
		panelWest.add(panelWestSouth, gbc_panelWestSouth);

		String[] playerBasicInfo = { "姓名", "球衣号码", "位置", "身高", "体重", "生日",
				"年龄", "球龄", "毕业学校" };
		Object[] pBIGET = getPlayerBasicInfo(vo);
		int gap1 = 27, y1 = -10;
		for (int i = 0; i < playerBasicInfo.length; i++) {
			JLabel l = new JLabel(playerBasicInfo[i] + ":" + pBIGET[i]);
			l.setBounds(30, y1 += gap1, 200, 15);
			panelWestSouth.add(l);
		}

		scrollPaneCenter = new JScrollPane();
		scrollPaneCenter
				.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		scrollPaneCenter
				.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
		contentPane.add(scrollPaneCenter, BorderLayout.CENTER);
		
		scrollPaneSouth = new JScrollPane();
		scrollPaneSouth.setPreferredSize(new Dimension(410, 100));
		scrollPaneSouth
				.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		contentPane.add(scrollPaneSouth, BorderLayout.EAST);
		
		displayData();

		
		displayMatches();
		
		LocalBLServiceManager.getRedisplayControllerBLService().register(this);
	}

	private void displayData() {
		
		contentPane0 = new JPanel();
		contentPane.setBackground(Color.white);
		contentPane0.setPreferredSize(new Dimension(600, height));
		contentPane0.setLayout(new BorderLayout(0, 0));
		JTabbedPane tabbedPane = new JTabbedPane(SwingConstants.TOP);
		contentPane0.add(tabbedPane, BorderLayout.CENTER);
		
		JPanel panelCenter = new JPanel();
		//panelCenter.setPreferredSize(new Dimension(600, height));
		tabbedPane.addTab("    详细数据     ", null, panelCenter, null);
		panelCenter.setLayout(null);
		
		int gap = 30, y = 0;
		String basicData[] = { "基础数据", "所属球队", "比赛场数",  "在场时间", "得分",
				"前场篮板", "后场篮板", "篮板", "三分出手数","三分命中数", "助攻", "抢断", "盖帽", "失误", "犯规" };
		Object[] itemsGetBasic = { "", vo.get所属球队(), vo.get比赛场数(),
				 vo.get在场时间() / 60, vo.get比赛得分(), vo.get前场篮板数(),
				vo.get后场篮板数(), vo.get篮板数(), vo.get三分出手数(),vo.get三分命中数(), vo.get助攻数(),
				vo.get断球数(), vo.get盖帽数(), vo.get失误数(), vo.get犯规数() };
		for (int i = 0; i < itemsGetBasic.length; i++) {
			JLabel l = new JLabel(basicData[i] + ":"
					+ formatDouble(itemsGetBasic[i]));
			l.setBounds(80, y += gap, 200, 50);
			panelCenter.add(l);
		}
		String highLevelData[] = { "高级数据", "效率", "得分近五场提升率", "篮板近五场提升率",
				"助攻近五场提升率", "GmSc效率值", "投篮命中率", "三分命中率", "罚球命中率", "篮板率",
				"进攻篮板率", "防守篮板率", "抢断率", "助攻率", "盖帽率", "失误率", "使用率" };
		Object[] itemsGetHigh = { "", vo.get效率(), vo.get得分近五场提升率(),
				vo.get篮板近五场提升率(), vo.get助攻近五场提升率(), vo.getGmSc效率值(),
				vo.get投篮命中率(), vo.get三分命中率(), vo.get罚球命中率(), vo.get篮板率(),
				vo.get进攻篮板率(), vo.get防守篮板率(), vo.get抢断率(), vo.get助攻率(),
				vo.get盖帽率(), vo.get失误率(), vo.get使用率() };
		y = 0;
		for (int i = 0; i < itemsGetHigh.length; i++) {
			JLabel l = new JLabel(highLevelData[i] + ":"
					+ formatDouble(itemsGetHigh[i]));
			l.setBounds(280, y += gap, 200, 50);
			panelCenter.add(l);
		}
		panelCenter.setBackground(Color.white);
		
		JPanel imagePanel = new JPanel();
		imagePanel.setBackground(Color.white);
		tabbedPane.addTab("    图表展现     ", null, imagePanel, null);
		imagePanel.setLayout(new BoxLayout(imagePanel, BoxLayout.Y_AXIS));
		
		/*try {
			List<PlayerVo> playervos = ((PlayerQueryBLService) RMIClientBLServiceManager
					.getBLService(PlayerQueryBLService.class)).query所有球员赛季表现四分位数("13-14", "投篮命中率")
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		
		JPanel chartPanel =getRadarChart();
		imagePanel.add(chartPanel);
		
		JPanel chartPanel2 =getLineChart();
		imagePanel.add(chartPanel2);
		
		scrollPaneCenter.setViewportView(contentPane0);
	}

	private void displayMatches() {
		try {
			List<MatchVo> matches = ((MatchQueryBLService) RMIClientBLServiceManager
					.getBLService(MatchQueryBLService.class)).queryByPlayer(
					vo.getName(), vo.get赛季());
			
			matches.sort((m1,m2)->(int)(m2.getDate()-m1.getDate()));

			info = matchToArray(matches, vo);

			TableModel model = new SortableTableModel(info, columns);
			table = new SortableTable(model);
			table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
			table.addDoubleClickOnDataListener(
					DetailsListenerFactory.getMatchDetailListener(season), 0, 1);
		} catch (Exception e1) {
			JOptionPane
					.showMessageDialog(this, "服务器连接发生异常\n" + e1.getMessage());
			e1.printStackTrace();
		}
		table.getColumnModel().getColumn(0).setPreferredWidth(110);
		table.getColumnModel().getColumn(1).setPreferredWidth(110);
		table.getColumnModel().getColumn(2).setPreferredWidth(110);
		table.getColumnModel().getColumn(3).setPreferredWidth(110);
		scrollPaneSouth.setViewportView(table);


	}
	private Object[] getPlayerBasicInfo(PlayerVo vo) {
		Object[] info = new Object[9];
		info[0] = vo.getName();
		info[1] = vo.getNumber() == -1 ? "N/A" : vo.getNumber();
		info[2] = vo.getPosition();
		info[3] = vo.getHeight()/12+""+"-"+vo.getHeight()%12;
		info[4] = vo.getWeight();
		info[5] = new SimpleDateFormat("yyyy-MM-dd").format(new Date(vo
				.getBirth()));
		info[6] = vo.getAge();
		info[7] = vo.getExp() == 1 ? "R" : vo.getExp();
		info[8] = vo.getSchool();
		return info;
	}

	private Object formatDouble(Object i) {
		if (i instanceof Double) {
			DecimalFormat df = new DecimalFormat("#.###");
			return df.format(i);
		}
		return i;
	}

	private Object[][] matchToArray(List<MatchVo> matches, PlayerVo player) {
		int length = matches.size();
		Object[][] info = new Object[length][4];
		for (int n = 0; n < length; n++) {
			MatchVo match = matches.get(n);
			info[n][0] = new SimpleDateFormat("yyyy-MM-dd").format(new Date(
					match.getDate()));
			info[n][1] = match.getTeam1() + "-" + match.getTeam2();
			info[n][2] = match.getTeam1Score() + ":" + match.getTeam2Score();
			int personalScore[] = { 0 };
			String playerName = player.getName();
			String playerBelongTo = player.get所属球队();
			boolean flag = match.getTeam1().equals(playerBelongTo);
			Set<PlayerScoreTableVo> playerPerformance = flag ? match
					.getTeam1PlayersScore() : match.getTeam2PlayersScore();
			playerPerformance.forEach(s -> {
				if (s.get球员名().equals(playerName)) {
					personalScore[0] = s.get个人得分();
				}
			});
			info[n][3] = personalScore[0];
		}

		return info;

	}
	
	private JPanel getRadarChart(){
		try {
			PlayerQueryBLService pbl=RMIClientBLServiceManager.getBLService(PlayerQueryBLService.class);
			vo=pbl.query场均数据ByName(vo.getName(), season);
		
		List<String> valueNames=Arrays.asList(new String[]{"投篮命中率","三分命中率","进攻篮板率","防守篮板率","助攻率","抢断率"});
		List<Double> maxValues=Arrays.asList(new Double[]{
				pbl.query所有球员赛季表现四分位数(season, vo->vo.get投篮命中率()).get(3).get投篮命中率(),
				pbl.query所有球员赛季表现四分位数(season, vo->vo.get三分命中率()).get(3).get三分命中率(),
				pbl.query所有球员赛季表现四分位数(season, vo->vo.get进攻篮板率()).get(3).get进攻篮板率(),
				pbl.query所有球员赛季表现四分位数(season, vo->vo.get防守篮板率()).get(3).get防守篮板率(),
				pbl.query所有球员赛季表现四分位数(season, vo->vo.get助攻率()).get(3).get助攻率(),
				pbl.query所有球员赛季表现四分位数(season, vo->vo.get抢断率()).get(3).get抢断率(),
		});
		List<Double> values=Arrays.asList(new Double[]{
				vo.get投篮命中率()/maxValues.get(0),vo.get三分命中率()/maxValues.get(1),vo.get进攻篮板率()/maxValues.get(2),vo.get防守篮板率()/maxValues.get(3),vo.get助攻率()/maxValues.get(4),vo.get抢断率()/maxValues.get(5)
		});
		List<Double> medianValues=Arrays.asList(new Double[]{
				pbl.query所有球员赛季表现四分位数(season, vo->vo.get投篮命中率()).get(1).get投篮命中率()/maxValues.get(0),
				pbl.query所有球员赛季表现四分位数(season, vo->vo.get三分命中率()).get(1).get三分命中率()/maxValues.get(1),
				pbl.query所有球员赛季表现四分位数(season, vo->vo.get进攻篮板率()).get(1).get进攻篮板率()/maxValues.get(2),
				pbl.query所有球员赛季表现四分位数(season, vo->vo.get防守篮板率()).get(1).get防守篮板率()/maxValues.get(3),
				pbl.query所有球员赛季表现四分位数(season, vo->vo.get助攻率()).get(1).get助攻率()/maxValues.get(4),
				pbl.query所有球员赛季表现四分位数(season, vo->vo.get抢断率()).get(1).get抢断率()/maxValues.get(5)
		});
		
		return Graphics.getRadarChart("球员能力", valueNames, values, medianValues);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	private JPanel getLineChart(){
		return new PlayerProgressPanel(vo);
	}

	@Override
	public void redisplay() {
		try {
			vo = ((PlayerQueryBLService) RMIClientBLServiceManager
					.getBLService(PlayerQueryBLService.class)).query场均数据ByName(
					vo.getName(), "13-14");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		vo.set三分命中数(Double.parseDouble((String) (formatDouble(vo.get三分出手数()))));
		
		displayMatches();
		displayData();
	}
}
